#' @TODO 多变量同一分组在一个boxplot中
#' @title 多变量同一分组在一个boxplot中
#' @description 多变量同一分组在一个boxplot中
#' @param input data.frame，输入数据
#' @param x_ 字符串向量，x轴坐标对应列
#' @param y_ 字符串向量，y轴坐标对应列
#' @param group_ 字符串向量，分组信息对应列
#' @param type_ y轴数值类型，比如说
#' @param color_in_p 字符串向量，分组对应颜色
#' @param x_angle 数字，x轴字体倾斜角度
#' @param style 单一字符串，可选box1，box2，vln。box1：白线中线箱线图；box2：填充半透明箱线图；vln：填充半透明的小提琴图
#' @export
#' @return ggplot对象
#' @author *WYK*
#'
Box_in_One_p <- function(
    input, x_, y_, group_, color_in_p = RColorBrewer::brewer.pal(4, "Set1"),
    x_angle = 45, style = "box1") {
  library(tidyverse)

  ignoreCase <- c(
    "NA", "NAN", "NaN", "NX", "MX", "TX", "Not Reported", "GX", "UNK", "-", "", " ",
    "unknown", "UNknown", "notreported", "gx", NA
  )

  input <- input %>%
    dplyr::filter(!group_ %in% ignoreCase)

  color_in_p <- color_in_p[seq_len(length(unique(input[[group_]])))]

  p4 <- switch(style,
    box1 = {
      ggplot(
        data = input,
        aes_string(x_, y_, fill = group_)
      ) +
        geom_boxplot(aes_string(col = group_),
          outlier.size = .2, outlier.shape = NA,
          width = .5,
          position = position_dodge(width = .63)
        ) +
        xlab(NULL) +
        ggpubr::theme_pubr(13) +
        theme(
          axis.text.x = element_text(angle = x_angle, hjust = 1, vjust = 1, size = 10),
          legend.position = "bottom",
          legend.title = element_blank()
        ) +
        ggpubr::stat_compare_means(
          aes(
            group = get0(group_),
            label = after_stat(p.signif)
          )
        ) +
        ggplot2::coord_cartesian(clip = "off") +
        scale_fill_manual(values = color_in_p) +
        scale_color_manual(values = color_in_p) +
        stat_summary(
          fun = median, geom = "crossbar", color = "white", width = 0.59, size = .2,
          position = position_dodge(width = .63)
        )
    },
    box2 = {
      ggplot(
        data = input,
        aes_string(x_, y_, fill = group_)
      ) +
        geom_boxplot(aes_string(col = group_),
          outlier.size = .2, outlier.shape = NA,
          width = .5,
          position = position_dodge(width = .63)
        ) +
        xlab(NULL) +
        ggpubr::theme_pubr(13) +
        theme(
          axis.text.x = element_text(angle = x_angle, hjust = 1, vjust = 1, size = 10),
          legend.position = "bottom"
        ) +
        ggpubr::stat_compare_means(
          aes(
            group = get0(group_),
            label = after_stat(p.signif)
          )
        ) +
        ggplot2::coord_cartesian(clip = "off") +
        scale_fill_manual(values = ggplot2::alpha(color_in_p, .75)) +
        scale_color_manual(values = color_in_p)
    },
    vln = {
      ggplot(
        data = input,
        aes_string(x_, y_, fill = group_)
      ) +
        # ggplot2::geom_violin()
        geom_violin(aes_string(col = group_),
          width = .5,
        ) +
        scale_fill_manual(values = ggplot2::alpha(color_in_p, .75)) +
        scale_color_manual(values = color_in_p) +
        xlab(NULL) +
        ggpubr::theme_pubr(13) +
        theme(
          axis.text.x = element_text(angle = x_angle, hjust = 1, vjust = 1, size = 10),
          legend.position = "bottom",
          legend.title = element_blank()
        ) +
        ggpubr::stat_compare_means(aes(group = get0(group_), label = after_stat(p.signif))) +
        ggplot2::coord_cartesian(clip = "off")
    },
    mix1 = {
      ggplot(
        data = input,
        aes_string(x_, y_, fill = group_)
      ) +
        geom_violin(alpha = .8, width = .7) +
        geom_boxplot(fill = "white", width = .1, outlier.shape = NA) +
        xlab(NULL) +
        ggpubr::theme_pubr() +
        scale_fill_manual(values = ggplot2::alpha(color_in_p, .75)) +
        ggpubr::stat_compare_means(aes(group = get0(group_), label = after_stat(p.signif))) +
        theme(
          axis.text.x = element_text(angle = x_angle, hjust = 1, vjust = 1, size = 10),
          legend.position = "bottom",
          legend.title = element_blank()
        )
    }
  )
  return(p4)
}


#'
#' @inheritParams BoxOne_p
#' @title 药敏预测专用Segment plot
#' @param size_ 字符串，点大小对应列名
#'
SegmentPoint_p <- function(input, x_, size_, y_) {
  library(tidyverse)

  p1 <- ggplot(data = input, aes(get0(x_), reorder(get0(y_), get0(x_)))) +
    geom_segment(aes_string(xend = 0, yend = y_), linetype = 2) +
    geom_point(aes_string(size = size_), col = RColorBrewer::brewer.pal(4, "Set1")[4]) +
    #   scale_size_continuous(range =c(2,8)) +
    #   scale_x_reverse(breaks = c(0, -0.3, -0.5),
    #                   expand = expansion(mult = c(0.01,.1))) + #左右留空
    ggpubr::theme_pubr() +
    labs(x = get0(size_), y = "", size = "-log10(P)") +
    theme(
      legend.position = "bottom",
      axis.ticks.y.right = element_blank(),
      plot.margin = unit(c(0.2, 0.2, 0.2, 0), "cm")
    )

  return(p1)
}

#' @TODO 两个data.frame中，数值列计算spearman相关性
#' @title 两个data.frame中，数值列计算spearman相关性
#' @description 两个data.frame中，数值列计算spearman相关性，df1为单一数值，df2中可以有多个数值列
#' @param df1 data.frame，输入数据
#' @param value_in_df1 单一字符串，df1中用于计算相关性的列
#' @param df2 字符串，用于与df1中数值列进行相关性计算。理想状态是，除了key那一列，其余的都是数值型向量，然后与df1中value_in_df1 进行相关性计算。
#' @param key_in_df1df2 字符串，df1与df2中共有信息列
#' @param p_adj_method c("holm", "hochberg", "hommel", "bonferroni", "BH", "BY", "fdr", "none")任意一个
#' @param cor_method 相关性计算方法。"pearson" "spearman" and "kendall"
#' @export
#' @return data.frame,对象
#' @author *WYK*
#'
Cor_OneAndMore <- function(df1, value_in_df1, df2, key_in_df1df2 = "sample",
                           cor_method = "spearman", p_adj_method = "BH") {
    require(tidyverse)
    require(psych)

    if (missing(value_in_df1)) {
        message("df1中缺少用于相关性分析的数值列，程序停止")
        return()
    }
    df1 <- df1[, c(key_in_df1df2, value_in_df1)]
    common_keys <- intersect(df2[[key_in_df1df2]], df1[[key_in_df1df2]])

    df1 <- df1[map_int(common_keys, ~ which(df1[[key_in_df1df2]] == .x)), ]
    df2 <- df2[map_int(common_keys, ~ which(df2[[key_in_df1df2]] == .x)), ]

    cor_res <- psych::corr.test(df2 %>% select(-key_in_df1df2),
        df1 %>% select(-key_in_df1df2),
        method = cor_method, adjust = p_adj_method
    )

    # type r p
    df3 <- inner_join(
        cor_res$r %>% as.data.frame() %>% rownames_to_column("type") %>% rename(rho = 2),
        cor_res$p.adj %>% as.data.frame() %>% rownames_to_column("type") %>% rename(p = 2)
    )

    df2_long <- df2 %>% pivot_longer(cols = -key_in_df1df2, values_to = "value", names_to = "type")
    #             sample              type value
    #    <chr>           <chr>             <dbl>
    #  1 TCGA-06-2567-01 Camptothecin_1003 -4.21

    ComplexDF <- left_join(df1, df2_long) %>%
        left_join(df3) %>%
        as.data.frame()

    return(ComplexDF)
}


# > head(tcga_df)
#            sample status time riskgroup   riskscore HR_group
# 1 TCGA-41-2571-01      1   26       Low -0.30868822        0
# 2 TCGA-16-0846-01      1  119       Low -0.24254558        0
# 3 TCGA-06-2559-01      1  150       Low -0.14951827        0

# > IC50[1:3,1:3]
#            sample Camptothecin_1003 Vinblastine_1004
# 1 TCGA-06-2567-01         -4.212059        -5.102575
# 2 TCGA-26-5132-01         -3.802283        -4.951003
# 3 TCGA-26-5133-01         -2.793420        -6.944809

# dfx <- Cor_OneAndMore(tcga_df, "riskscore", IC50)
# top_type <- dfx %>%
#     filter(p < 0.05) %>%
#     select(type, rho) %>%
#     distinct() %>%
#     slice_max(rho, n = 10) %>%
#     pull(1)

# top_pos_durg_df <- dfx %>%
#     filter(type %in% top_type) %>%
#     rename("Drug" = "type", "logIC50" = "value") %>%
#     left_join(tcga_df %>% select(sample, riskgroup))

# a <- SegmentPoint_p(top_pos_durg_df, x_ = 'rho', size_ = 'p', y_ = 'Drug')

# b <- Box_in_One_p(input = top_pos_durg_df,
#     x_ = "Drug", y_ = "logIC50",
#     group_ = "riskgroup", color_in_p = RColorBrewer::brewer.pal(4, "Set1")[1:2]
# )

# c <- ggpubr::ggarrange(a,b)

# plotout(p = c,w = 7.4,h = 4,od = '/Pub/Users/wangyk/Project_wangyk/Codelib_YK/some_scr/DataVisualization/',name = 'aaa')
